import { _decorator, physics, Texture2D, Node, v3, Material, Vec3, systemEvent, SystemEventType, EventTouch, CameraComponent, geometry, Touch, PhysicsSystem, ModelComponent, ToggleComponent, LabelComponent, EditBoxComponent, Button, Toggle } from "cc";
import BaseView from '../game/BaseView';
import GDef from '../config/GDef';
import GD from '../config/GD';
import SdkMgr from '../../Script/tyq3.x/SdkMgr';
import Tool from '../tool/Tool'
import TyqEventMgr from '../../Script/tyq3.x/tyq-event-mgr';
const { ccclass, property, menu } = _decorator;


@ccclass("RaycastTest")
export class RaycastTest extends BaseView {


    @property({
        type: Node
    })
    nodeArms: Node = null;

    @property({ type: CameraComponent })
    readonly camera: CameraComponent = null as any;




    private _ray: geometry.Ray = new geometry.Ray();
    private _maxDistance: number = 100;
    private _mask: number = 0xffffffff;
    private touchId: number = -1;
    private touchIdTo: number = -1;

    public set maxDistance(v: number) {
        this._maxDistance = v;
    }
    onLoad() {
        this.on(GDef.wdEvent.startRay, this.onLevelStart);
        this.on(GDef.wdEvent.stopRay, this.startFight);
        this.on(GDef.wdEvent.addTeach, this.addTeach);
    }
    start() {
        this.maxDistance = this._maxDistance;
        this.onLevelStart();
    }
    addTeach() {
        console.log("ray:" + GD.intTeach);
        if (GD.intTeach <= 1) this.onLevelStart(true);
    }
    onLevelStart(force: boolean) {
        console.log("Ray onLevelStart");
        if (!force && GD.intTeach < 1) return;
        systemEvent.off(SystemEventType.TOUCH_START, this.onTouchStart, this);
        systemEvent.off(SystemEventType.TOUCH_MOVE, this.onTouchMove, this);
        systemEvent.off(SystemEventType.TOUCH_END, this.onTouchEnd, this);
        systemEvent.off(SystemEventType.TOUCH_CANCEL, this.onTouchEnd, this);
        systemEvent.on(SystemEventType.TOUCH_START, this.onTouchStart, this);
        systemEvent.on(SystemEventType.TOUCH_MOVE, this.onTouchMove, this);
        systemEvent.on(SystemEventType.TOUCH_END, this.onTouchEnd, this);
        systemEvent.on(SystemEventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
    startFight() {
        console.log("startFight");
        systemEvent.off(SystemEventType.TOUCH_START, this.onTouchStart, this);
        systemEvent.off(SystemEventType.TOUCH_MOVE, this.onTouchMove, this);
        systemEvent.off(SystemEventType.TOUCH_END, this.onTouchEnd, this);
        systemEvent.off(SystemEventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }


    onTouchStart(touch: Touch, event: EventTouch) {
        console.log("onTouchStart:" + this.touchId + ",cellArm:" + this.getCellArm(this.touchId));
        this.camera.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);
        let self = this;
        if (PhysicsSystem.instance.raycast(this._ray, this._mask, this._maxDistance, true)) {
            const r = PhysicsSystem.instance.raycastResults;
            for (let i = 0; i < r.length; i++) {
                let obj = r[i];
                if (obj.collider.node.name == "preCell") {
                    const preCell = obj.collider.node.getComponent("preCell");
                    if (preCell.getId() < 15) continue;
                    this.touchId = preCell.getId();
                    this.touchIdTo = this.touchId;
                    console.log("onTouchStart:" + this.touchId + ",cellArm:" + this.getCellArm(this.touchId));
                    this.emit(GDef.wdEvent.pressCell, this.touchId, this.touchId, touch.getLocation());
                    break;
                }
                else if (obj.collider.node.name == "preYilong") {
                    TyqEventMgr.ins.sendEvent('观看激励视频-翼龙宝箱');
                    SdkMgr.ins.showRewardAd("观看激励视频-翼龙宝箱", () => {
                        TyqEventMgr.ins.sendEvent('观看完激励视频-翼龙宝箱');
                        self.emit(GDef.wdEvent.playEffect, "CoinCollect");
                        let coin = Math.max(GD.getCastHumanCost(), GD.getCastDinoCost()) * 10;
                        self.emit(GDef.wdEvent.addCoin, coin, GDef.nodeAd.getWorldPosition());
                        obj.collider.node.active = false;
                    }, () => {
                    }, () => {
                    });
                    break;
                }
            }
        }
    }
    onTouchMove(touch: Touch, event: EventTouch) {
        if (this.touchId >= 0) {
            this.camera.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);

            if (PhysicsSystem.instance.raycast(this._ray, this._mask, this._maxDistance, true)) {
                const r = PhysicsSystem.instance.raycastResults;
                for (let i = 0; i < r.length; i++) {
                    let obj: physics.PhysicsRayResult = r[i];
                    if (obj.collider.node.name == "Plane") {
                        this.emit(GDef.wdEvent.moveArm, this.touchId, obj.hitPoint);
                    }
                    if (obj.collider.node.name == "preCell") {
                        const preCell = obj.collider.node.getComponent("preCell");
                        if (preCell.getId() < 15) continue;
                        this.touchIdTo = preCell.getId();
                        console.log("move To cell:" + this.touchIdTo);
                        this.emit(GDef.wdEvent.dragCell, this.touchId, this.touchIdTo, touch.getLocation());
                    }
                    if (obj.collider.node.name == "lajitong") {
                        let materialLight = new Material();
                        materialLight.copy(GDef.materialLightSrc);
                        Tool.loadAsset(GDef.pack2, GDef.textureLajitong, Texture2D).then((texture) => {
                            materialLight.setProperty("mainTexture", texture);
                            Tool.setModelMaterial(obj.collider.node, materialLight);
                        });
                    }
                }
            }
        }
    }
    onTouchEnd(touch: Touch, event: EventTouch) {
        this.emit(GDef.wdEvent.dragCell, -1);
        let jsonArmFrom = this.getCellArm(this.touchId);
        let jsonArmTo = this.getCellArm(this.touchIdTo);
        let emitSuccess = false;
        //触碰垃圾桶
        if (PhysicsSystem.instance.raycast(this._ray, this._mask, this._maxDistance, true)) {
            const r = PhysicsSystem.instance.raycastResults;
            for (let i = 0; i < r.length; i++) {
                let obj: physics.PhysicsRayResult = r[i];
                if (obj.collider.node.name == "lajitong") {
                    //消灭一只
                    this.emit(GDef.wdEvent.setArm, this.touchId, null);
                    emitSuccess = true;
                    //垃圾桶
                    let materialNormal = new Material();
                    materialNormal.copy(GDef.materialNormalSrc);
                    Tool.loadAsset(GDef.pack2, GDef.textureLajitong, Texture2D).then((texture) => {
                        materialNormal.setProperty("mainTexture", texture);
                        Tool.setModelMaterial(obj.collider.node, materialNormal);
                    });
                    //金币
                    this.emit(GDef.wdEvent.playEffect, "CoinCollect");
                    let coin = Math.max(GD.getCastHumanCost(), GD.getCastDinoCost()) * 0.5;
                    let pos = Tool.getPos(GDef.getRoot().children[0], obj.collider.node, v3(0, 0, 0));
                    this.emit(GDef.wdEvent.addCoin, coin, pos);
                    break;
                }
            }
        }
        //相同的合成
        console.log("onTouchEnd jsonArmFrom:" + JSON.stringify(jsonArmFrom));
        console.log("onTouchEnd jsonArmTo:" + JSON.stringify(jsonArmTo));
        if (!emitSuccess && this.touchId != this.touchIdTo && jsonArmFrom && jsonArmTo && jsonArmFrom.armType == jsonArmTo.armType && jsonArmFrom.type == jsonArmTo.type) {
            console.log("合成");
            //是否有变异
            let exRatio = 0;
            if (jsonArmFrom.quality == 2) exRatio++;
            if (jsonArmTo.quality == 2) exRatio++;
            //合成后
            console.log(jsonArmFrom.armType == GDef.TypeHuman ? "humanType" : "dinoType");
            let jsonArmType = jsonTables.getJsonTableObj(jsonArmFrom.armType == GDef.TypeHuman ? "humanType" : "dinoType", jsonArmFrom.type + 1);
            let arrArmUp = jsonTables.getJsonTable(jsonArmFrom.armType == GDef.TypeHuman ? "human" : "dino");
            //合成变异.
            if (jsonArmType && Math.random() + exRatio > 1.5) {
                console.log("合成1只变异");
                for (let i = 0; i < arrArmUp.length; i++) {
                    //找到变异
                    if (arrArmUp[i].type == jsonArmType.Tid && arrArmUp[i].quality == 2) {
                        console.log("找到变异");
                        this.emit(GDef.wdEvent.setArm, this.touchIdTo, arrArmUp[i]);
                        //消灭一只
                        this.emit(GDef.wdEvent.setArm, this.touchId, null);
                        emitSuccess = true;
                        break;
                    }
                }
            }
            //合成普通
            if (jsonArmType && !emitSuccess) {
                console.log("合成1只普通");
                console.log("jsonArmUp:", jsonArmType);
                for (let i = 0; i < arrArmUp.length; i++) {
                    //找到普通
                    if (arrArmUp[i].type == jsonArmType.Tid && arrArmUp[i].quality == 1) {
                        console.log("找到普通");
                        this.emit(GDef.wdEvent.setArm, this.touchIdTo, arrArmUp[i]);
                        //消灭一只
                        this.emit(GDef.wdEvent.setArm, this.touchId, null);
                        emitSuccess = true;
                        break;
                    }
                }
            }
        }
        //不相同的换位置
        if (!emitSuccess && jsonArmFrom) {
            this.emit(GDef.wdEvent.releaseArm, this.touchId, this.touchIdTo);
            if (!jsonArmTo) GD.decPlayerArm(this.touchId);
        }
        this.touchId = -1;
        this.touchIdTo = -1;
    }
    getCellArm(id1: number) {

        let len = this.nodeArms.children.length;
        for (let i = len - 1; i >= 0; i--) {
            if (this.nodeArms.children[i] && this.nodeArms.children[i].getComponent("preArm")?.cellId == id1) {
                return this.nodeArms.children[i].getComponent("preArm").jsonArm;
            }
        }
        return null;
    }

}
